<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="酒店" prop="hotelId">
              <el-select v-model="queryParams.hotelId" filterable clearable placeholder="请选择酒店" :loading="loading">
                <el-option v-for="item in options" :key="item.id" :label="item.hotelName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="房间名称" prop="roomType">
              <el-input v-model="queryParams.roomType" placeholder="请输入房间名称类型" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['hotel:hotelRooms:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['hotel:hotelRooms:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['hotel:hotelRooms:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hotel:hotelRooms:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="hotelRoomsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="" align="center" prop="id" v-if="false" />
        <el-table-column label="酒店id" align="center" prop="hotelId" v-if="false" />
        <el-table-column label="排序号" align="center" prop="orderNum" />
        <el-table-column label="酒店名称" align="center" prop="hotelName" />
        <el-table-column label="房间类型" align="center" prop="roomType" />
        <el-table-column label="房间预览图片" align="center" prop="roomImgurlUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.roomImgurlUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="轮播图" align="center" prop="carouselImagesUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.carouselImagesUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description" v-if="false" />
        <el-table-column label="原价" align="center" prop="price">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.price) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="label">
          <template #default="scope">
            <dict-tag :options="ter_hotel_fac" :value="scope.row.label ? scope.row.label.split(',') : []"/>
          </template>
        </el-table-column>
        <el-table-column label="总数量" align="center" prop="totalQuantity" />
        <el-table-column label="房间规格" align="center" prop="specification" />
        <el-table-column label="开关标识" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="ter_room_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="友情提示" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['hotel:hotelRooms:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['hotel:hotelRooms:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="日历统计" placement="top">
              <el-button link type="primary" icon="Grid" @click="handleCalendar(scope.row)" v-hasPermi="['hotel:hotelRooms:query']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改酒店房型管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="hotelRoomsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="酒店" prop="hotelId">
              <el-select v-model="form.hotelId" filterable clearable placeholder="请选择酒店" :loading="loading" >
                <el-option v-for="item in options" :key="item.id" :label="item.hotelName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间类型" prop="roomType">
              <el-input v-model="form.roomType" placeholder="请输入房间名称类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间预览图片" prop="roomImgurl">
              <image-upload v-model="form.roomImgurl" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轮播图" prop="carouselImages">
              <image-upload v-model="form.carouselImages" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <editor v-model="form.description" :min-height="192" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序号" prop="teroomHprice">
              <el-input-number v-model="form.orderNum" :min="0" :step="10" />
            </el-form-item>
            <el-form-item label="原价" prop="price">
              <el-input-number v-model="form.price" :min="0.01" placeholder="元" :precision="2" :step="1.0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量" prop="totalQuantity">
              <el-input-number v-model="form.totalQuantity" :min="0" :step="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间规格" prop="specification">
              <el-input v-model="form.specification" type="textarea" placeholder="请输入房间规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="友情提示" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入友情提示" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签" prop="label">
              <el-checkbox-group v-model="form.label">
                <el-checkbox v-for="dict in ter_hotel_fac" :key="dict.value" :label="dict.value">
                    {{dict.label}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开关标识" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in ter_room_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogEdit.visible" title="修改日期信息" width="500px">
      <el-form>
        <el-form-item label="可用数量">
          <el-input-number v-model="editForm.availableQuantity" :min="0" />
        </el-form-item>
        <el-form-item label="销售价格">
          <el-input-number v-model="editForm.finalPrice" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogEdit.visible = false">取消</el-button>
        <el-button type="primary" @click="saveDateEdit">暂存</el-button>
      </template>
    </el-dialog>
    <el-dialog :title="dialogCalendar.title" v-model="dialogCalendar.visible" width="800px">
      <div v-loading="calendarLoading">
        <el-calendar v-model="calendarDate">
          <template #header="{ date }">
            <div class="flex justify-between items-center">
              <span>{{ date }}</span>
              <el-button-group>
                <el-button @click="changeMonth(-1)">上个月</el-button>
                <el-button @click="calendarDate = new Date()">本月</el-button>
                <el-button @click="changeMonth(1)">下个月</el-button>
                <el-button @click="batchSubmit()">批量提交</el-button>
              </el-button-group>
            </div>
          </template>
          <template #date-cell="{ data }">
            <div class="h-full p-1" @dblclick="handleDateDblClick(data.day)" :class="{ 'bg-blue-100': modifiedDates.has(data.day) }">
              <div class="date">{{ data.day.split('-').slice(2).join('-') }}</div>
              <template v-if="calendarData[data.day]">
                <div class="text-xs text-gray-600">空闲：{{ calendarData[data.day].booked }}</div>
                <div class="text-xs text-green-600">￥{{ calendarData[data.day].price }}</div>
              </template>
            </div>
          </template>
        </el-calendar>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="HotelRooms" lang="ts">
import { listHotelRooms, getHotelRooms, delHotelRooms, addHotelRooms, updateHotelRooms } from '@/api/hotel/hotelRooms';
import { listPriceCalendar, inventoryModify } from '@/api/hotel/priceCalendar';
import { HotelRoomsVO, HotelRoomsQuery, HotelRoomsForm } from '@/api/hotel/hotelRooms/types';
import { HotelsVO } from '@/api/hotel/hotels/types';
import { selectComb } from '@/api/hotel/hotels';
import { floatToFixed2, formatToFraction, convertToInteger } from '@/utils/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ter_hotel_fac, ter_room_status } = toRefs<any>(proxy?.useDict('ter_hotel_fac', 'ter_room_status'));
const calendarLoading = ref(false);
const hotelRoomsList = ref<HotelRoomsVO[]>([]);
const options = ref<HotelsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const hotelRoomsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogCalendar = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogEdit = reactive({
  visible: false,
  day: ''
});
const editForm = reactive({
  availableQuantity: 0,
  finalPrice: 0
});
const modifiedDates = reactive(new Set<string>());
const initFormData: HotelRoomsForm = {
  id: undefined,
  hotelId: undefined,
  hotelName: undefined,
  roomType: undefined,
  roomImgurl: undefined,
  carouselImages: undefined,
  description: undefined,
  price: undefined,
  label: [],
  totalQuantity: undefined,
  availableQuantity: undefined,
  specification: undefined,
  remark: undefined,
  status: undefined,
  orderNum: undefined
}
const data = reactive<PageData<HotelRoomsForm, HotelRoomsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hotelId: undefined,
    hotelName: undefined,
    roomType: undefined,
    roomImgurl: undefined,
    carouselImages: undefined,
    description: undefined,
    price: undefined,
    label: undefined,
    totalQuantity: undefined,
    availableQuantity: undefined,
    specification: undefined,
    orderNum: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    hotelId: [
      { required: true, message: "酒店id不能为空", trigger: "change" }
    ],
    roomType: [
      { required: true, message: "房间名称类型不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "原价不能为空", trigger: "blur" }
    ],
    totalQuantity: [
      { required: true, message: "总数量不能为空", trigger: "blur" }
    ]
  }
});
const handleDateDblClick = (day: string) => {
  const currentData = calendarData.value[day];
  if (currentData) {
    editForm.availableQuantity = currentData.booked;
    editForm.finalPrice = currentData.price;
    dialogEdit.day = day;
    dialogEdit.visible = true;
  }
};
const saveDateEdit = () => {
  calendarData.value[dialogEdit.day] = {
    booked: editForm.availableQuantity,
    price: editForm.finalPrice
  };
  modifiedDates.add(dialogEdit.day);
  dialogEdit.visible = false;
};
const { queryParams, form, rules } = toRefs(data);

/** 查询酒店房型管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listHotelRooms(queryParams.value);
  hotelRoomsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const calendarDate = ref(new Date());
const currentRoomId = ref<string | number>();
const calendarData = ref<Record<string, { booked: number; price: string | number }>>({});

const handleCalendar = async (row: HotelRoomsVO) => {
  currentRoomId.value = row.id;
  dialogCalendar.title = `${row.roomType} 房型统计`;
  dialogCalendar.visible = true;
  calendarLoading.value = true;
  await loadCalendarData();
  calendarLoading.value = false;
};

const loadCalendarData = async () => {
  if (!currentRoomId.value) return;
  modifiedDates.clear();
  const res = await listPriceCalendar({
    roomId: currentRoomId.value,
    pageNum: 0,
    pageSize: 0
  });
  calendarData.value = res.data.reduce((acc, cur) => {
    acc[cur.priceDay] = { booked: cur.availableQuantity, price: formatToFraction(cur.finalPrice) };
    return acc;
  }, {});
};
const batchSubmit = async () => {
  if (!currentRoomId.value || modifiedDates.size === 0) return;
  const datas = Array.from(modifiedDates).map((day) => ({
    availableQuantity: calendarData.value[day].booked,
    finalPrice: convertToInteger(calendarData.value[day].price),
    dates: day
  }));
  try {
    await inventoryModify({ datas: datas, roomId: currentRoomId.value });
    proxy?.$modal.msgSuccess("批量提交成功");
    modifiedDates.clear();
    await loadCalendarData(); // 重新加载最新数据
  } catch (error) {
    console.error('提交失败:', error);
  }
};
/** 提交按钮**/
const changeMonth = (offset: number) => {
  const newDate = new Date(calendarDate.value);
  newDate.setMonth(newDate.getMonth() + offset);
  calendarDate.value = newDate;
  // loadCalendarData();
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  hotelRoomsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: HotelRoomsVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 获取下拉对象
const fetchData = async () => {
  loading.value = true;
  const response = await selectComb();
  options.value = response.data;
  loading.value = false;
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加酒店房型管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HotelRoomsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getHotelRooms(_id);
  Object.assign(form.value, res.data);
  form.value = {
    ...res.data,
    price: formatToFraction(res.data.price),
    label: (form.value.label?.toString() || '')
      .split(',')
      .map((item) => item.trim())
      .filter((item) => item !== '')
  };
  dialog.visible = true;
  dialog.title = "修改酒店房型管理";
}
/** 提交按钮 */
const submitForm = () => {
  const selectedItem = options.value.find((item) => item.id === form.value.hotelId);
  if (selectedItem) {
    form.value.hotelName = selectedItem.hotelName;
  }
  hotelRoomsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const data = {
        ...form.value,
        label: form.value.label.join(","),
        price: convertToInteger(form.value.price)
      } as unknown as HotelRoomsForm;
      if (form.value.id) {
        await updateHotelRooms(data).finally(() =>  buttonLoading.value = false);
      } else {
        await addHotelRooms(data).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HotelRoomsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除酒店房型管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delHotelRooms(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

onMounted(() => {
  getList();
  fetchData();
});
</script>
<style lang="css" scoped>
.calendar-cell {
  transition: all 0.2s;
  min-height: 90px;
  cursor: pointer;
}

.calendar-cell:hover {
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.el-icon-edit {
  opacity: 0.5;
  transition: opacity 0.2s;
}

.el-icon-edit:hover {
  opacity: 1;
  color: #409EFF;
}
</style>
